package com.stox.services.screener.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.stox.services.screener.model.intf.ScreenMatch;
import com.stox.services.screener.util.ScanRegistry;

public class Scan<T extends ScreenMatch> {

	private boolean cancelRequested;
	private final String id;
	private double completionPercentage;
	private final Map<T, Boolean> matches = new HashMap<>();
	
	public Scan(String id) {
		this.id = id;
		ScanRegistry.register(this);
	}

	public double getCompletionPercentage() {
		return completionPercentage;
	}

	public void setCompletionPercentage(double completionPercentage) {
		this.completionPercentage = completionPercentage;
	}

	public String getId() {
		return id;
	}
	
	public void addMatch(T match){
		synchronized(matches){
			matches.put(match, Boolean.FALSE);
		}
	}
	
	
	public boolean isCancelRequested() {
		return cancelRequested;
	}
	
	public void cancel() {
		this.cancelRequested = true;
	}
	
	public List<T> getUnServedMatches(){
		synchronized(matches){
			List<T> unServedMatches = new ArrayList<>();
			for(T match : matches.keySet()){
				Boolean served = matches.get(match);
				if(null == served || !served){
					unServedMatches.add(match);
				}
			}
			for(T match : unServedMatches){
				matches.put(match, Boolean.TRUE);
			}
			return unServedMatches;
		}
	}
	
}
